package hy.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import hy.beans.User;
import hy.service.UserService;
import hy.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/user/login")
    public Map login(User user) {
        Map m=new HashMap<>();
        try {
            User userDB = userService.login(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("name", userDB.getName());
            m.put("token", JWTUtils.getToken(payload));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  m;
    }

    @PostMapping("/user/test")
    public Map test(@RequestHeader String token) {
        //这里不是为了验签，只是为了获取数据
//        String token = request.getHeader("token");
        System.out.println(token);
        DecodedJWT verify = JWTUtils.verify(token);
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);
        Map m=new HashMap<>();
        m.put("msg","请求成功");
        return m;
    }
}